package com.chenyuxin.ilp;

import com.chenyuxin.ilp.service.file.Impl.MinioServiceImpl;
import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import io.minio.*;

import io.minio.errors.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import io.minio.http.Method;
import org.springframework.http.MediaType;

import javax.management.ObjectName;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class MinioTest {
    @Value("${minio.bucket.files}")
    private String bucket;
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioServiceImpl minioService;
    // 上传文件
    @Test
    public void upload() {
        String filePath = "/Users/chenyuxin/Downloads/1-Linux系统基本操作（2025）.pdf";
        String extension = filePath.substring(filePath.lastIndexOf('.') + 1);
        String fileName = "/702449a2c24f47919ff5ee62a38ed4d7/13"+"/"+filePath.substring(filePath.lastIndexOf("/")+1);
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        if(extensionMatch!=null){
            mimeType = extensionMatch.getMimeType();
        }
        try{
            UploadObjectArgs testBucket = UploadObjectArgs.builder()
                    .bucket(bucket)
                    .object(fileName)
                    .filename(filePath)
                    .contentType(mimeType)
                    .build();
            minioClient.uploadObject(testBucket);
            System.out.println("上传成功");
        }catch (Exception exception){
            exception.printStackTrace();
            System.out.println("上传失败！");
        }
    }
    @Test
    void upload2(){
        String filePath = "/Users/chenyuxin/Downloads/1-Linux系统基本操作（2025）.pdf";
        String fileName = "/702449a2c24f47919ff5ee62a38ed4d7/13"+"/"+filePath.substring(filePath.lastIndexOf("/")+1);
        minioService.upload(filePath,bucket,fileName,".pdf");
    }
    @Test
     void getPreviewUrl() throws Exception {
        String fileName = "/702449a2c24f47919ff5ee62a38ed4d7/preview/461aa4bf35f944e19bcff1977e381ace.pdf";
        String previewUrl =  minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucket)
                        .object(fileName)
                        .expiry(2, TimeUnit.HOURS)  // 过期时间 2 小时
                        .build()
        );
        System.out.println(previewUrl);
    }
    @Test
    void delete() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        RemoveObjectArgs testBucket = RemoveObjectArgs.builder()
                .bucket(bucket).object("English.docx").build();
        minioClient.removeObject(testBucket);
    }
    @Test
    void move(){
        String newObjectName = "/e440adff71c04ea892dfe4db55e45d1e/语文/ppt/第二单元/1-Linux系统基本操作（2025）.pdf";
        String oldObjectName = "/e440adff71c04ea892dfe4db55e45d1e/1-Linux系统基本操作（2025）.pdf";
        String downloadFilePath = "";
        try {
            String fileName = newObjectName.substring(newObjectName.lastIndexOf('/') + 1);
            // 下载文件到本地指定路径
            downloadFilePath = "/Users/chenyuxin/比赛/2025服外软件设计校赛/Service-Outsourcing-Competition-Project/rear/intelligent-learning-platform/src/main/resources/tempfile/"+fileName;  // 本地文件保存路径
            GetObjectArgs getObjectArgs = GetObjectArgs.builder()
                    .bucket(bucket)
                    .object(oldObjectName)
                    .build();
            InputStream inputStream = minioClient.getObject(getObjectArgs);
            try (FileOutputStream outputStream = new FileOutputStream(downloadFilePath)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
            System.out.println("文件下载成功，保存路径：" + downloadFilePath);
        } catch (Exception e) {
            System.err.println("MinIO客户端发生异常: " + e);
        }
        // 上传文件到新路径
        String extension = newObjectName.substring(newObjectName.lastIndexOf('.') + 1);
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        if(extensionMatch!=null){
            mimeType = extensionMatch.getMimeType();
        }
        // 上传文件到新路径
        try {
            UploadObjectArgs testBucket = UploadObjectArgs.builder()
                    .bucket(bucket)
                    .object(newObjectName)
                    .filename(downloadFilePath)
                    .contentType(mimeType)
                    .build();
            minioClient.uploadObject(testBucket);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        File localFile = new File(downloadFilePath);
        if (localFile.exists() && localFile.isFile()) {
            boolean deleted = localFile.delete();
            if (deleted) {
                System.out.println("本地文件删除成功！");
            } else {
                System.err.println("本地文件删除失败！");
            }
        } else {
            System.err.println("文件不存在，无法删除：" + downloadFilePath);
        }


        // 删除旧文件
        try {
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(bucket)
                    .object(oldObjectName)
                    .build()
            );
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        System.out.println("文件路径修改成功！");
    }
    @Test
    void download(){
        try{

            String objectName = "/2e502446ff484980989f0f1e6d7bfa5b/27/29/关于Vmware虚拟机Ubuntu系统的克隆及静态ip配置.pdf"; // MinIO 对象路径
            String localFilePath = "/Users/chenyuxin/Downloads/关于Vmware虚拟机Ubuntu系统的克隆及静态ip配置.pdf"; // 本地存储路径
            // 下载文件
            InputStream stream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucket)
                            .object(objectName)
                            .build()
            );

            // 将流写入本地文件
            FileOutputStream fileOutputStream = new FileOutputStream(localFilePath);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = stream.read(buf)) != -1) {
                fileOutputStream.write(buf, 0, bytesRead);
            }
            fileOutputStream.close();
            stream.close();

            System.out.println("文件下载成功：" + localFilePath);
        } catch (MinioException e) {
            System.err.println("MinIO 错误：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
